package com.example.cake.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cake.common.Result;
import com.example.cake.entity.DTO.SysOrderDTO;
import com.example.cake.entity.SysCustomer;
import com.example.cake.entity.SysOrder;
import com.example.cake.service.SysCustomerService;
import com.example.cake.service.SysOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/order")
public class SysOrderController {
    @Autowired
    private SysOrderService sysOrderService;
    @Autowired
    private SysCustomerService sysCustomerService;

    @PostMapping("/list")
    public Result list(@RequestBody SysOrderDTO sysOrderDTO) {
        LambdaQueryWrapper<SysOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysOrder::getUserId,sysOrderDTO.getUserId());
        Page<SysOrder> page = new Page<>(sysOrderDTO.getPage(), sysOrderDTO.getLimit());
        return Result.success(sysOrderService.page(page,lqw));
    }
    @PostMapping("/adminList")
    public Result adminList(@RequestBody SysOrderDTO sysOrderDTO) {
        Page<SysOrder> page = new Page<>(sysOrderDTO.getPage(), sysOrderDTO.getLimit());
        Page<SysOrder> orderPage = sysOrderService.page(page, null);
        orderPage.getRecords().forEach(item->{
            LambdaQueryWrapper<SysCustomer> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SysCustomer::getId,item.getUserId());
            SysCustomer one = sysCustomerService.getOne(lqw);
            item.setSysCustomer(one);
        });

        return Result.success(orderPage);
    }

    @PostMapping("/add")
    public Result add(@RequestBody SysOrder sysOrder) {
        sysOrder.setCreateTime(DateUtil.toLocalDateTime(new Date()));
        sysOrder.setState("待支付");
        long time = new Date().getTime();
        String time1 = String.valueOf(2023 + time);
        sysOrder.setId(time1);
        return Result.success(sysOrderService.save(sysOrder));
    }

    @PostMapping("/remove")
    public Result add(@RequestBody String id) {
        return Result.success(sysOrderService.removeById(id));
    }

    @PostMapping("/update")
    public Result update(@RequestBody SysOrder sysOrder) {
        return Result.success(sysOrderService.updateById(sysOrder));
    }
}
